﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using umbraco;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.interfaces;
using umbraco.presentation.cache;
using umbraco.uicontrols;
using umbraco.controls;
using Commerce.Common;

namespace CommerceForUmbraco.adminSection.commerce
{
    public partial class editProductOptionTemplate : umbraco.BasePages.UmbracoEnsuredPage
    {
        public TabPage TemplateTab;

        AttributeTemplate thisProductOptionTemplate;

        protected void Page_Load(object sender, EventArgs e)
        {
            string templateId = Request.QueryString.Get("id");
            thisProductOptionTemplate = new AttributeTemplate(int.Parse(templateId));

            if (!IsPostBack)
            {
                LiteralTemplateID.Text = thisProductOptionTemplate.TemplateID.ToString();
                TextBoxName.Text = thisProductOptionTemplate.AttributeName;
                TextBoxDescription.Text = thisProductOptionTemplate.Description;

                DropDownListOptionType.Items.Clear();
                AttributeTypesCollection optionTypes = new AttributeTypesCollection();
                optionTypes = new AttributeTypesCollection().Load();
                for (int i = 0; i < optionTypes.Count; i++ )
                {
                    DropDownListOptionType.Items.Add(new ListItem(optionTypes[i].AttributeType,optionTypes[i].AttributeTypeID.ToString()));
                }
                DropDownListOptionType.SelectedValue = thisProductOptionTemplate.AttributeTypeID.ToString();
            }

            this.Pane1.Text = "Edit Product Option";
            this.pp_id.Text = "Option ID";
            this.pp_name.Text = "Option Name";
            this.pp_description.Text = "Display Name";
            this.pp_type.Text = "Option Type";

        }

        private umbraco.uicontrols.TabView GetDashboardPanel()
        {
            umbraco.uicontrols.TabView tabview =
                (umbraco.uicontrols.TabView)FindControlRecursive(this.Page.Master, "tabControl");
            return tabview;
        }

        public static Control FindControlRecursive(Control Root, string Id)
        {
            if (Root.ID == Id)
                return Root;

            foreach (Control Ctl in Root.Controls)
            {
                Control FoundCtl = FindControlRecursive(Ctl, Id);
                if (FoundCtl != null)
                    return FoundCtl;
            }

            return null;
        }

        private void save_click(object sender, ImageClickEventArgs e)
        {
            if (this.SaveProduct(this.TextBoxName.Text, base.Request.QueryString["id"]))
            {
                base.ClientTools.ShowSpeechBubble(0, ui.Text("speechBubbles", "Product Option Saved"), "");
            }
            else
            {
                base.ClientTools.ShowSpeechBubble(0, ui.Text("speechBubbles", "commerceItemErrorHeader"), ui.Text("speechBubbles", "commerceItemErrorText"));
            }
        }

        private bool SaveProduct(string optionName, string templateId)
        {
            int tempId = -1;
            AttributeTemplate productOption;
            
            if (Int32.TryParse(templateId, out tempId))
            {
                productOption = new AttributeTemplate("TemplateID", tempId);
            }
            else
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0}", "Couldn't save product because productOptionID is invalid."));

                return false;
            }

            try
            {
                productOption.AttributeName = this.TextBoxName.Text;
                productOption.Description = this.TextBoxDescription.Text;
                productOption.AttributeTypeID = Int32.Parse(this.DropDownListOptionType.SelectedValue);

                productOption.Save("Commerce for Umbraco");

                return true;
            }
            catch (Exception e)
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0} -- {1}", e.Message, e.StackTrace));

                return false;
            }
        }


        #region load routines
        protected override void OnInit(EventArgs e)
        {
            // Tab setup
            TemplateTab = tabControl.NewTabPage("Product Options");
            TemplateTab.Controls.Add(Pane1);

            // Template Tab
            ImageButton save = TemplateTab.Menu.NewImageButton();
            save.Click += new ImageClickEventHandler(this.save_click);
            save.AlternateText = "Save";
            save.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            base.Load += new EventHandler(this.Page_Load);
            this.InitializeComponent();
            base.OnInit(e);
        }

        private umbraco.cms.businesslogic.web.DocumentType GetContentPageDocumentType()
        {
            return umbraco.cms.businesslogic.web.DocumentType.GetByAlias("ContentPage");
        }

        private void InitializeComponent()
        {
        }
        #endregion


    }
}